package com.hzdp.web.action.account.ajax;

import org.springframework.beans.factory.annotation.Autowired;

import com.hzdp.entity.UserAccount;
import com.hzdp.sms.service.SmsService;
import com.hzdp.user.service.UserAccountService;
import com.hzdp.web.action.AjaxBaseAction;
import com.hzdp.web.action.account.AccountConstants;
import com.hzdp.web.action.util.MobileRegexValidator;
import com.hzdp.web.captcha.JCaptchaService;
import com.hzdp.web.util.CookieUtil;

public class AjaxLoginAction extends AjaxBaseAction {

	public static final int SUCCESS = 1;
	public static final int InvalidCaptcha = 5;
	public static final int InvalidUserAccount = 2;

	private String phone;
	private String p;
	private String captcha;

	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public void setP(String p) {
		this.p = p;
	}

	@Autowired
	private SmsService smsService;
	@Autowired
	private UserAccountService userAccountService;
	@Autowired
	private JCaptchaService jCaptchaService;

	@Override
	protected void executeJson() {
		UserAccount userAccount = userAccountService.findByMobile(phone);
		// checkpassword
		if (userAccount == null) {
			type = InvalidUserAccount;
			msg = "手机号码或密码不正确";
			return;
		}

		if (userAccountService.checkPwd(p, userAccount)) {
			String token = userAccountService.login(userAccount.getId(), true);
			if (token != null && !token.isEmpty()) {
				CookieUtil.setRootCookie(request, response, AccountConstants.Token, token);
			}
			type = SUCCESS;
		} else {
			type = InvalidUserAccount;
			msg = "手机号码或密码不正确";
		}
	}

	@Override
	public int getType() {
		return type;
	}

	@Override
	public int getStatus() {
		return status;
	}

	@Override
	protected boolean checkParams() {
		// 手机号码校验
		if (phone == null || phone.isEmpty() || !MobileRegexValidator.valid(phone)) {
			type = InvalidUserAccount;
			msg = "手机号码有误";
			return false;
		}

		if (p == null || p.isEmpty() || p.length() < 6 || p.length() > 32) {
			type = InvalidUserAccount;
			msg = "手机号码或密码不正确";
			return false;
		}

		return checkCaptcha();
	}

	// 图片验证码校验
	private boolean checkCaptcha() {
		if (captcha == null || captcha.isEmpty()) {
			type = InvalidCaptcha;
			msg = "图形验证码错误";
			return false;
		}

		if (!jCaptchaService.check(getUUID(), captcha)) {
			msg = "图形验证码错误";
			type = InvalidCaptcha;
			return false;
		}

		return true;
	}

	@Override
	public String getMsg() {
		return msg;
	}

}
